import random
from Conversation import Conversation
from waveapi import document

def message(message, blip):
	query = Conversation.gql("WHERE father = :1 AND value > :2", message, 0)
	conversations = query.fetch(1000)
	if conversations:
		maxValue = 0
		for conversation in conversations:
			value = conversation.value + conversation.son.value
			if value > 0:
				maxValue += value
		answer = random.randint(0, maxValue)
		for conversation in conversations:
			value = conversation.value + conversation.son.value
			if value > 0:
				answer -= value
				if answer <= 0:
					response = conversation.son.text
					newBlip = blip.CreateChild()
					newBlip.GetDocument().SetText(response)
#					addGadget(newBlip)
					break

def addGadget(newBlip):
	gadget = document.Gadget('http://tooangel-wave.appspot.com/public/gadget.xml')
	newBlip.GetDocument().AppendElement(gadget)

